package com.yzmoney.wechat.service;

import com.yzmoney.common.constant.Constants;
import com.yzmoney.common.constant.PropertyUtils;
import com.yzmoney.common.util.HttpClientUtils;
import com.yzmoney.common.util.JDKStackTrace;
import com.yzmoney.common.util.JsonUtils;
import com.yzmoney.wechat.model.general.GeneralReturnCode;
import com.yzmoney.wechat.model.token.JsToken;
import com.yzmoney.wechat.model.token.JsTokenJson;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 获取access_token
 *
 * @author DOVE
 */
@Service
public class WechatJsTokenService {
    private static Logger logger = Logger.getLogger(WechatJsTokenService.class);

    @Autowired
    private JsToken jsToken;

    @Autowired
    private WechatAccessTokenService wechatAccessTokenService;

    private static String baseJsTokenUrl = PropertyUtils.getValue("JS_TOKEN_URL", "", Constants.GZH_PATH);

    /**
     * 获取jsAccess_token
     *
     * @return
     */
    public String getJsToken() {
        Date now = new Date();
        Date last = jsToken.getLastGetTime();
        if (jsToken.getTicket() == null || (((now.getTime() - last.getTime()) / 1000) > 7000)) {
            httpGetJSTon();
        }
        return jsToken.getTicket();
    }

    /**
     * http 请求获取access_token
     */
    public boolean httpGetJSTon() {
        try {
            String accessToken = wechatAccessTokenService.getGZHAccessToken();
            String url = getJsTokenUrl(accessToken);
            String replyJsonStr = HttpClientUtils.getString(url);
            JsTokenJson jsTokenJson = JsonUtils.toObject(replyJsonStr, JsTokenJson.class);
            if (jsToken == null) {
                GeneralReturnCode errCode = JsonUtils.toObject(replyJsonStr, GeneralReturnCode.class);
                logger.info(Constants.LOGPRIFIX + "请求 jsToken[失败]. " + errCode.toString());
                return false;
            } else {
                jsToken.setTicket(jsTokenJson.getTicket());
                jsToken.setLastGetTime(new Date());
                logger.info(Constants.LOGPRIFIX + "请求 jsToken[成功]. " + jsToken.toString());
                return true;
            }
        } catch (Exception e) {
            logger.warn(Constants.LOGPRIFIX + "请求 jsToken[失败]. " + JDKStackTrace.getJDKStrack(e));
            return false;
        }
    }

    /**
     * 拼接公众号
     * @return
     */
    private static String getJsTokenUrl(String access_token){
        String jsTokenUrl = baseJsTokenUrl
        		+"?access_token="
                + access_token
                + "&type=jsapi";
        return  jsTokenUrl;
    }
}
